<script setup lang="ts">
import { ref, reactive, watch, onMounted } from "vue";
import type { FormRules } from "element-plus";
import { message } from "@/utils/message";
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  treeInfo: {
    type: Object,
    default: () => {}
  }
});
const ruleFormRef = ref(null);
const dialogFormVisible = ref(props.visible);
const emits = defineEmits(["update:visible", "refresh"]);
// 监听父组件传入的visible变化
watch(
  () => props.visible,
  newVal => {
    dialogFormVisible.value = newVal;
  }
);
const handleCancel = () => {
  emits("update:visible", false);
};
const handSave = async () => {
  await ruleFormRef.value.validate();
  if (props.treeInfo.id) {
    emits("refresh");
  } else {
    emits("update:visible", false);
    emits("refresh");
  }
};
interface FormModel {
  name: string;
  id: string;
}
// 选中的数据源
const form = reactive<FormModel>({
  name: "",
  id: ""
});
const validateName = (
  rule: any,
  value: string,
  callback: (error?: Error) => void
) => {
  const regex = /^[A-Za-z\d\u4e00-\u9fa5]{1,30}$/;
  if (!regex.test(value)) {
    callback(new Error("请输入数字、字母、汉字"));
  } else {
    callback();
  }
};
const rules: FormRules<FormModel> = {
  name: [
    { required: true, message: "请输入类型名称", trigger: "blur" },
    { min: 1, max: 30, message: "长度在 1 到 30 个字符", trigger: "change" },
    { validator: validateName, trigger: "blur" }
  ]
};
</script>

<template>
  <el-dialog
    v-model="dialogFormVisible"
    width="960"
    :title="props.treeInfo.id ? '编辑巡更项目类型' : '新增巡更项目类型'"
    draggable
    :before-close="handleCancel"
  >
    <el-form
      ref="ruleFormRef"
      :model="form"
      :rules="rules"
      label-width="auto"
      label-position="left"
      status-icon
    >
      <el-form-item label="类型名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入类型名称" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handSave">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss"></style>
